package actions;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import db.DBModel;

public class InsertUserAction extends Action{
	
	public ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request,HttpServletResponse response) {
		try {
			Map<String,String> errorMessages = new HashMap<String,String>();
			
			DBModel database = new DBModel();
			
			String username = request.getParameter("userName");
			String email = request.getParameter("email");
			String password = request.getParameter("password");
			String bio = request.getParameter("bio");
			
			if(database.usernameExists(username)) {
				errorMessages.put("username", "Username " +username+ " already exists");
			}
			else if(database.emailExists(email, 0)) {
				errorMessages.put("email", "Email " +email+ " already exists");
			}
			
			if(errorMessages.size() > 0) {
				request.setAttribute("errorMessages", errorMessages);
				System.out.println("invalid input");
				return mapping.findForward("invalid");
			}
			else {
				database.insertUser(username, email, password, bio);
				database.commit();
			}
			database.close();			
			return mapping.findForward("success");
		}catch (Exception e){
			e.printStackTrace();
			request.setAttribute("error", e.toString());
			return mapping.findForward("fail");
		}	
	}
}
